package com.xebest.web.controller.restapi;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.xebest.api.dto.XeVenOrderEnteringLogisticsDetailResponseDTO;
import com.xebest.api.dto.XeVenOrderEnteringLogisticsPageDTO;
import com.xebest.api.dto.XeVenOrderEnteringLogisticsRequestDTO;
import com.xebest.api.dto.XeVenOrderEnteringLogisticsResponseDTO;
import com.xebest.common.base.pagedto.XePageInfoDto;
import com.xebest.common.util.XeBaseUtil;
import com.xebest.constant.XeErrorCode;
import com.xebest.web.form.XeVenOrderEnteringLogisticsForm;
import com.xebest.web.service.XeVenOrderEnteringLogisticsService;
import com.xebest.web.view.XeVenOrderEnteringLogisticsDetailView;
import com.xebest.web.view.XeVenOrderEnteringLogisticsView;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 手动创建物流接口
 *
 * @author 袁世林
 */
@RestController
@RequestMapping("restApi/enteringLogistics")
public class XeVenOrderEnteringLogisticsRestApi {

    private Logger log = LoggerFactory.getLogger(XeVenOrderEnteringLogisticsRestApi.class);


    @Autowired
    private XeVenOrderEnteringLogisticsService enteringLogisticsService;


    /**
     * 查询创建的物流列表
     *
     * @author 袁世林
     */
    @RequestMapping("queryEnteringLogisticsList")
    public @ResponseBody
    XeVenOrderEnteringLogisticsPageDTO<XeVenOrderEnteringLogisticsResponseDTO> queryEnteringLogisticsList(@RequestBody XeVenOrderEnteringLogisticsRequestDTO dto) {

        log.info("查询创建的物流列表---入参: {}", JSON.toJSONString(dto));
        XeVenOrderEnteringLogisticsPageDTO<XeVenOrderEnteringLogisticsResponseDTO> pageDTO = null;
        try {
            pageDTO = new XeVenOrderEnteringLogisticsPageDTO<XeVenOrderEnteringLogisticsResponseDTO>();
            XeVenOrderEnteringLogisticsForm form = new XeVenOrderEnteringLogisticsForm();
            PageHelper.startPage(dto.getXePageDto().getPageNum(), dto.getXePageDto().getPageSize());

            form.setLogtsCode(dto.getLogtsCode());
            form.setOrderId(dto.getOrderId());

            //2.查询列表数据
            List<XeVenOrderEnteringLogisticsView> resultList = this.enteringLogisticsService.queryEnteringLogisticsList(form);
//            List<XeVenOrderEnteringLogisticsResponseDTO> responseDto = JSONArray.parseArray(JSONArray.toJSONString(resultList), XeVenOrderEnteringLogisticsResponseDTO.class);
            List<XeVenOrderEnteringLogisticsResponseDTO> responseDto = new ObjectMapper().readValue(JSONArray.toJSONString(resultList), new TypeReference<List<XeVenOrderEnteringLogisticsResponseDTO>>() { });

            for (int i = 0; i < resultList.size(); i++) {
                //省
                String provinceName = XeBaseUtil.baseUtil.getAreaName(Integer.parseInt(resultList.get(i).getCaProvinceId()));
                //市
                String cityName = XeBaseUtil.baseUtil.getAreaName(Integer.parseInt(resultList.get(i).getCaCityId()));
                //区
                String areaName = XeBaseUtil.baseUtil.getAreaName(Integer.parseInt(resultList.get(i).getCaAreaId()));
                //详细地址
                String caStreet = resultList.get(i).getCaStreet();
                //组装收货地址

                String address = provinceName + "-" + cityName + "-" + areaName + "-" + caStreet;

                responseDto.get(i).setAddress(address);

            }

            XePageInfoDto<?> pageInfo = new XePageInfoDto(resultList);
            pageDTO.setList(responseDto);
            pageDTO.setXePageInfoDto(pageInfo);
            pageDTO.setStatus(XeErrorCode.PORJECT_SUCCESS);
            return pageDTO;

        } catch (Exception e) {

            log.error("查询创建的物流列表---接口异常：{}", e);
            pageDTO.setStatus(XeErrorCode.PORJECT_ERROR);

        }
        return pageDTO;
    }

    /**
     * 根据订单号查询物流相关信息
     *
     * @author 袁世林
     */
    @RequestMapping("queryOrderLogisticsInfo")
    public @ResponseBody
    XeVenOrderEnteringLogisticsResponseDTO queryOrderLogisticsInfo(@RequestBody XeVenOrderEnteringLogisticsRequestDTO dto) {

        log.info("根据订单号查询物流相关信息---入参: {}", JSON.toJSONString(dto));
        XeVenOrderEnteringLogisticsResponseDTO responseDTO = null;
        try {
            responseDTO = new XeVenOrderEnteringLogisticsResponseDTO();
            if (null == dto || StringUtils.isBlank(dto.getOrderId())) {
                responseDTO.setStatus(XeErrorCode.PORJECT_PARAM_ERROR);
                responseDTO.setMsg("缺少必要参数！！！");
                return responseDTO;
            }

            XeVenOrderEnteringLogisticsForm form = new XeVenOrderEnteringLogisticsForm();
            form.setOrderId(dto.getOrderId());
            //判断该订单号是否已经创建物流 :0.自动录入 1.手工录入生效 2.手工录入未生效',如果是1，则不能创建
            Integer createLogisticType = this.enteringLogisticsService.queryOrderLogisticsCreateLogisticType(dto.getOrderId());
            if (createLogisticType != null && createLogisticType == 1) {
                responseDTO.setCreateLogisticType(1);
                responseDTO.setStatus(XeErrorCode.PORJECT_SUCCESS);
                return responseDTO;
            }


            XeVenOrderEnteringLogisticsView resultView = this.enteringLogisticsService.queryOrderLogisticsInfo(form);

            if (resultView != null) {
                responseDTO = JSONObject.parseObject(JSONObject.toJSONString(resultView),
                        XeVenOrderEnteringLogisticsResponseDTO.class);
                //省
                String provinceName = XeBaseUtil.baseUtil.getAreaName(Integer.parseInt(resultView.getCaProvinceId()));
                //市
                String cityName = XeBaseUtil.baseUtil.getAreaName(Integer.parseInt(resultView.getCaCityId()));
                //区
                String areaName = XeBaseUtil.baseUtil.getAreaName(Integer.parseInt(resultView.getCaAreaId()));
                //详细地址
                String caStreet = resultView.getCaStreet();
                //组装收货地址

                String address = provinceName + "-" + cityName + "-" + areaName + "-" + caStreet;
                responseDTO.setAddress(address);
                responseDTO.setStatus(XeErrorCode.PORJECT_SUCCESS);
            } else {
                responseDTO.setStatus(XeErrorCode.PORJECT_PARAM_ERROR);
                responseDTO.setMsg("请输入已发货的订单号");
            }

            return responseDTO;

        } catch (Exception e) {

            log.error("根据订单号查询物流相关信息---异常：{}", e);
            responseDTO.setStatus(XeErrorCode.PORJECT_ERROR);
        }
        return responseDTO;
    }

    /**
     * 保存新建的物流
     *
     * @author 袁世林
     */
    @RequestMapping("saveEnteringLogistics")
    public @ResponseBody
    XeVenOrderEnteringLogisticsResponseDTO saveEnteringLogistics(@RequestBody XeVenOrderEnteringLogisticsRequestDTO dto) {

        log.info("保存新建的物流---入参: {}", JSON.toJSONString(dto));
        XeVenOrderEnteringLogisticsResponseDTO responseDTO = null;
        try {
            responseDTO = new XeVenOrderEnteringLogisticsResponseDTO();

            if (dto == null || StringUtils.isBlank(dto.getLogtsCode()) || StringUtils.isBlank(dto.getOrderId())) {
                responseDTO.setStatus(XeErrorCode.PORJECT_PARAM_ERROR);
                return responseDTO;
            }

            XeVenOrderEnteringLogisticsForm form = new XeVenOrderEnteringLogisticsForm();
            form.setOrderId(dto.getOrderId());
            form.setLogtsCode(dto.getLogtsCode());
            List<XeVenOrderEnteringLogisticsForm> formList = JSONArray.parseArray(JSONArray.toJSONString(dto.getDetailRequestDTO()),
                    XeVenOrderEnteringLogisticsForm.class);

            this.enteringLogisticsService.saveEnteringLogistics(form, formList);

            responseDTO.setStatus(XeErrorCode.PORJECT_SUCCESS);
            return responseDTO;

        } catch (Exception e) {
            log.error("保存新建的物流---异常：{}", e);
            responseDTO.setStatus(XeErrorCode.PORJECT_ERROR);
        }
        return responseDTO;
    }


    /**
     * 根据物流单号查看详情
     *
     * @author 袁世林
     */
    @RequestMapping("queryEnteringLogisticsBylogsCode")
    public @ResponseBody
    XeVenOrderEnteringLogisticsResponseDTO queryEnteringLogisticsBylogsCode(@RequestBody XeVenOrderEnteringLogisticsRequestDTO dto) {

        log.info("根据物流单号查看详情---入参: {}", JSON.toJSONString(dto));
        XeVenOrderEnteringLogisticsResponseDTO responseDTO = null;
        try {
            responseDTO = new XeVenOrderEnteringLogisticsResponseDTO();
            if (null == dto || dto.getId() == null) {
                responseDTO.setStatus(XeErrorCode.PORJECT_PARAM_ERROR);
                return responseDTO;
            }

            XeVenOrderEnteringLogisticsForm form = new XeVenOrderEnteringLogisticsForm();
            form.setId(dto.getId());

            //2.查询列表数据
            XeVenOrderEnteringLogisticsView resultView = this.enteringLogisticsService.queryEnteringLogisticsById(form);

            List<XeVenOrderEnteringLogisticsDetailView> detailView = resultView.getDetailView();

//            List<XeVenOrderEnteringLogisticsDetailResponseDTO> detailResponseDTOList = JSONArray.parseArray(JSONArray.toJSONString(detailView),
//                    XeVenOrderEnteringLogisticsDetailResponseDTO.class);
            List<XeVenOrderEnteringLogisticsDetailResponseDTO> detailResponseDTOList = new ObjectMapper().readValue(JSONArray.toJSONString(detailView), new TypeReference<List<XeVenOrderEnteringLogisticsDetailResponseDTO>>() { });

            responseDTO = JSONObject.parseObject(JSONObject.toJSONString(resultView), XeVenOrderEnteringLogisticsResponseDTO.class);
            responseDTO.setDetailResponseDTO(detailResponseDTOList);

            //省
            String provinceName = XeBaseUtil.baseUtil.getAreaName(Integer.parseInt(resultView.getCaProvinceId()));
            //市
            String cityName = XeBaseUtil.baseUtil.getAreaName(Integer.parseInt(resultView.getCaCityId()));
            //区
            String areaName = XeBaseUtil.baseUtil.getAreaName(Integer.parseInt(resultView.getCaAreaId()));
            //详细地址
            String caStreet = resultView.getCaStreet();
            //组装收货地址

            String address = provinceName + "-" + cityName + "-" + areaName + "-" + caStreet;

            responseDTO.setAddress(address);

            responseDTO.setStatus(XeErrorCode.PORJECT_SUCCESS);
            return responseDTO;

        } catch (Exception e) {

            log.error("根据物流单号查看详情---异常：{}", e);
            responseDTO.setStatus(XeErrorCode.PORJECT_ERROR);
        }
        return responseDTO;
    }


    /**
     * 编辑新建的物流
     *
     * @author 袁世林
     */
    @RequestMapping("editEnteringLogistics")
    public @ResponseBody
    XeVenOrderEnteringLogisticsResponseDTO editEnteringLogistics(@RequestBody XeVenOrderEnteringLogisticsRequestDTO dto) {

        log.info("编辑新建的物流---入参: {}", JSON.toJSONString(dto));
        XeVenOrderEnteringLogisticsResponseDTO responseDTO = null;
        try {

            responseDTO = new XeVenOrderEnteringLogisticsResponseDTO();
            if (dto == null || dto.getId() == null) {
                responseDTO.setStatus(XeErrorCode.PORJECT_PARAM_ERROR);
                return responseDTO;
            }

            XeVenOrderEnteringLogisticsForm form = new XeVenOrderEnteringLogisticsForm();
            form.setId(dto.getId());

            List<XeVenOrderEnteringLogisticsForm> formList = JSONArray.parseArray(JSONArray.toJSONString(dto.getDetailRequestDTO()),
                    XeVenOrderEnteringLogisticsForm.class);

            this.enteringLogisticsService.editEnteringLogistics(form, formList);

            responseDTO.setStatus(XeErrorCode.PORJECT_SUCCESS);
            return responseDTO;

        } catch (Exception e) {
            log.error("编辑新建的物流---异常：{}", e);
            responseDTO.setStatus(XeErrorCode.PORJECT_ERROR);
        }
        return responseDTO;
    }


    /**
     * 作废新建的物流
     *
     * @param dto
     * @return XeVenOrderEnteringLogisticsResponseDTO
     * @author 袁世林
     */
    @RequestMapping("cancelEnteringLogistics")
    public @ResponseBody
    XeVenOrderEnteringLogisticsResponseDTO cancelEnteringLogistics(@RequestBody XeVenOrderEnteringLogisticsRequestDTO dto) {

        log.info("作废新建的物流---入参: {}", JSON.toJSONString(dto));
        XeVenOrderEnteringLogisticsResponseDTO responseDTO = null;
        try {
            responseDTO = new XeVenOrderEnteringLogisticsResponseDTO();

            if (dto.getId() == null) {
                responseDTO.setStatus(XeErrorCode.PORJECT_PARAM_ERROR);
                return responseDTO;
            }


            this.enteringLogisticsService.cancelEnteringLogistics(dto.getId());

            responseDTO.setStatus(XeErrorCode.PORJECT_SUCCESS);
            return responseDTO;

        } catch (Exception e) {
            log.error("作废新建的物流---异常：{}", e);
            responseDTO.setStatus(XeErrorCode.PORJECT_ERROR);
        }
        return responseDTO;
    }

    /**
     * 删除新建的物流
     *
     * @author 袁世林
     */
    @RequestMapping("deletelEnteringLogistics")
    public @ResponseBody
    XeVenOrderEnteringLogisticsResponseDTO deletelEnteringLogistics(@RequestBody XeVenOrderEnteringLogisticsRequestDTO dto) {

        log.info("刪除新建的物流---入参: {}", JSON.toJSONString(dto));
        XeVenOrderEnteringLogisticsResponseDTO responseDTO = null;
        try {
            responseDTO = new XeVenOrderEnteringLogisticsResponseDTO();

            if (dto.getId() == null) {
                responseDTO.setStatus(XeErrorCode.PORJECT_PARAM_ERROR);
                return responseDTO;
            }


            this.enteringLogisticsService.deletelEnteringLogistics(dto.getId());

            responseDTO.setStatus(XeErrorCode.PORJECT_SUCCESS);
            return responseDTO;

        } catch (Exception e) {
            log.error("刪除新建的物流---异常：{}", e);
            responseDTO.setStatus(XeErrorCode.PORJECT_ERROR);
        }
        return responseDTO;
    }

}
